package com.gopay.bis.service.bank.impl.certify;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.dao.bankorder.BankContractSerialInfoDAO;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.CertChannelCode;
import com.gopay.common.domain.bank.ExPayBaseMessage;
import com.gopay.common.domain.bank.foundation.IdentityInfoMessage;
import com.gopay.common.domain.bis.BisBankContractSerialInfo;
import com.gopay.common.util.MD5Util;
import com.gopay.remote.bank.foundation.BankCardCertifyRemoteService;
import com.gopay.remote.bank.foundation.RealNameCertifyRemoteService;

/** 
 * @ClassName: HFDatasCertifyServiceImpl 
 * @Description: 华付四要素银行卡鉴权
 * @author ShenJun 
 * @date 2017年6月15日 上午10:46:46  
 */

public class HFDatasCertifyServiceImpl implements BankCardCertifyRemoteService {
	
	private Logger logger = LoggerFactory.getLogger(HFDatasCertifyServiceImpl.class);

	@Resource(name = "hfdatasProviderClient")
	RealNameCertifyRemoteService hfdatasProviderClient;
	
	@Resource(name = "bankContractSerialInfoDAO")
    private BankContractSerialInfoDAO bankContractSerialInfoDAO;
	/* (非 Javadoc) 
	 *  
	 *  
	 * @param base
	 * @return 
	 * @see com.gopay.remote.bank.foundation.BankCardCertifyRemoteService#mobileCertify(com.gopay.common.domain.bank.foundation.IdentityInfoMessage) 
	 */
	@Override
	public Result bankCardCertify(ExPayBaseMessage base) {
		logger.error("HFDatasCertifyServiceImpl.bankCardCertify  华付银行卡四要素鉴权    start----- ");
		Result result = new Result(false);
        try {
        	//是否鉴权过   
        	int isExist = isExistCardInfo(base);
        	if (isExist >= 0) {
        		if(isExist == 1){
        			// 鉴权成功过
            		result.setModel("flag", true);
                    result.setModel("retMsg", "鉴权通过");
        		} else {
        			// 鉴权不成功过
            		result.setModel("flag", false);
                    result.setModel("retMsg", "鉴权不通过");
        		}
        		logger.error("以前鉴权过，直接返回结果！" + result.getModel("retMsg"));
        	} else {
        		// 调用实名认证接口
    		 	IdentityInfoMessage identityInfoMessage=new IdentityInfoMessage();
 				identityInfoMessage.setCardHolder(base.getCardHolder());
     			identityInfoMessage.setBankCardNo(base.getCardNo());
     			identityInfoMessage.setMobileNumber(base.getMediaId());
     			identityInfoMessage.setIdentityCode(base.getIdentityCode());
     			String channelMak = base.getSpecial2();
     			if(CertChannelCode.HUAFU4.value.equals(channelMak)){
     				identityInfoMessage.setChannelMak(CertChannelCode.HUAFU4.value);
     			} else if(CertChannelCode.HUAFU2.value.equals(channelMak)){
     				identityInfoMessage.setChannelMak(CertChannelCode.HUAFU2.value);
     			} else {
     				identityInfoMessage.setChannelMak(CertChannelCode.HUAFU4.value);
     			}
     			
     			result = hfdatasProviderClient.realNameCertify(identityInfoMessage);
     			logger.error("以前没有鉴权过，调用接口，返回result：" + ToStringBuilder.reflectionToString(result));
     			if(result.isSuccess()
     					&& !ProcCodeConstants.PROC_CODE_100E5303.equals(result.getResultCode())){
     				if((boolean)result.get("flag")){
     					//鉴权通过
     					saveContractPass(base);
     					result.setModel("flag", true);
     	                result.setModel("retMsg", "鉴权通过");
     				} else if(!(boolean)result.get("flag")){
     					//鉴权不通过
     					saveContractNotPass(base);
     					result.setModel("flag", false);
     	                result.setModel("retMsg", result.getModel("retMsg"));
     				}
     			}
        	}
        	result.setSuccess(true);
			logger.error("HFDatasCertifyServiceImpl.bankCardCertify  华付银行卡四要素鉴权    end----- ");
        }  catch (Exception ex) {
        	logger.error("HFDatasCertifyServiceImpl.bankCardCertify  华付银行卡四要素鉴权    exception----- ");
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6076);
        }
        return result;
	}
        
	 /**
     * 校验卡信息是否鉴权过
     * 
     * @param message
     * @return  1鉴权过，成功；0鉴权过，没成功；-1没有鉴权过
     */
    public int isExistCardInfo(ExPayBaseMessage message) {
        String elementsValue = MD5Util
                .sign(message.getIdentityCode() + message.getCardHolder() + message.getCardNo() + message.getMediaId());
        message.setSpecial4(elementsValue);
        //logger.error("elementsValue:" + elementsValue);
        BisBankContractSerialInfo serialInfo = getContractInfoByCard(message);
        //logger.error("serialInfo:" + serialInfo);
        if (serialInfo != null ) {
        	if("01".equals(serialInfo.getContractState())){
        		//鉴权过，成功
        		return 1;
        	} else{
        		//鉴权过，没成功
        		return 0;
        	}
        } else {
        	//没有鉴权过
            return -1;
        }
        
    }
    
    /**
     * 新建签约流水信息
     * 
     * @param message
     * 
     */
    public void saveContractPass(ExPayBaseMessage message) {
        BisBankContractSerialInfo bisBankContractSerialInfo = new BisBankContractSerialInfo();
        bisBankContractSerialInfo.setBankCode(message.getBank());
        bisBankContractSerialInfo.setBankBizProdCode(BisBankBusinessProd._19.value);
        bisBankContractSerialInfo.setIntrfaceChannelCode(BisBankInterfaceChannel._14.value);
        bisBankContractSerialInfo.setCardNo(message.getCardNo());
        String enementsValue = MD5Util
                .sign(message.getIdentityCode() + message.getCardHolder() + message.getCardNo() + message.getMediaId());
        bisBankContractSerialInfo.setElementsValue(enementsValue);
        bisBankContractSerialInfo.setSerialNumber(message.getAgrmtNo());
        bisBankContractSerialInfo.setContractDesc("hfdatas");
        bisBankContractSerialInfo.setContractState("01");
        bankContractSerialInfoDAO.insertContractSerialInfo(bisBankContractSerialInfo);
    }
    
    
    /**
     * 新建签约流水信息
     * 
     * @param message
     * 
     */
    public void saveContractNotPass(ExPayBaseMessage message) {
        BisBankContractSerialInfo bisBankContractSerialInfo = new BisBankContractSerialInfo();
        bisBankContractSerialInfo.setBankCode(message.getBank());
        bisBankContractSerialInfo.setBankBizProdCode(BisBankBusinessProd._19.value);
        bisBankContractSerialInfo.setIntrfaceChannelCode(BisBankInterfaceChannel._14.value);
        bisBankContractSerialInfo.setCardNo(message.getCardNo());
        String enementsValue = MD5Util
                .sign(message.getIdentityCode() + message.getCardHolder() + message.getCardNo() + message.getMediaId());
        bisBankContractSerialInfo.setElementsValue(enementsValue);
        bisBankContractSerialInfo.setSerialNumber(message.getAgrmtNo());
        bisBankContractSerialInfo.setContractDesc("hfdatas");
        bisBankContractSerialInfo.setContractState("02");
        bankContractSerialInfoDAO.insertContractSerialInfo(bisBankContractSerialInfo);
    }
    /**
     * 根据卡号获取签约流水数据
     * 
     * @param message
     * @return
     */
    public BisBankContractSerialInfo getContractInfoByCard(ExPayBaseMessage message) {
        BisBankContractSerialInfo bisBankContractSerialInfo = new BisBankContractSerialInfo();
        bisBankContractSerialInfo.setBankCode(message.getBank());
        bisBankContractSerialInfo.setBankBizProdCode(BisBankBusinessProd._19.value);
        bisBankContractSerialInfo.setIntrfaceChannelCode(BisBankInterfaceChannel._14.value);
       // bisBankContractSerialInfo.setCardNo(message.getCardNo());
        bisBankContractSerialInfo.setElementsValue(message.getSpecial4());
        bisBankContractSerialInfo.setContractDesc("hfdatas");
        bisBankContractSerialInfo = bankContractSerialInfoDAO.getContractInfobyCardAndEleValue(bisBankContractSerialInfo);
        return bisBankContractSerialInfo;
    }

}
